/********************************************/
/*	Copyright (C) 2018 Gong Li Bin			*/
/*	Project:	GmRm2000-1.0.0				*/
/*	Author:		gong_libin					*/
/*	Date:		2018_07_01					*/
/*	File:		GmPcap.go					*/
/********************************************/

package main

import (
	"os"
	"fmt"
	"log"
	"flag"
	"time"
	P "proto"

	"github.com/google/gopacket"
	"github.com/google/gopacket/pcap"
)

const (
	GMP_SNAPLEN		= 8092
	GMP_PROMISC		= false
	GMP_TIMTOUT		= time.Second * 30
	GMP_FILTERS		= "tcp and dst port 80"
)
func main()  {
	var hlp = flag.Bool("h", false, "show help")
	var ver = flag.Bool("v", false, "show version")
	var dev = flag.String("d", "eth0", "set device")

	flag.Parse()

	if true == *hlp {
		gmPcapHelp()
		os.Exit(0)
	}
	if true == *ver {
		gmPcapVersion()
		os.Exit(0)
	}

	hdl, err := pcap.OpenLive(*dev, GMP_SNAPLEN, GMP_PROMISC, GMP_TIMTOUT)
	if nil != err {log.Fatal(err)}
	defer hdl.Close()

	err = hdl.SetBPFFilter(GMP_FILTERS)
	if nil != err {log.Fatal(err)}
	defer hdl.Close()

	pkt := gopacket.NewPacketSource(hdl, hdl.LinkType())
	for p := range pkt.Packets() {
		gmPcapParse(p)
	}

}
func gmPcapParse(p gopacket.Packet)  {
	buf := p.Data()

	mac := P.NewGmMac(buf)
	mac.GmPrint()

	ip := P.NewGmIP(buf[14:34])
	ip.GmPrint()

	tcp := P.NewGmTcp(buf[34:54])
	tcp.GmPrint()

	off := 14 + int(ip.IPhl) * 4 + int(tcp.ThOff) * 4

	if len(buf) > off {
		http := P.NewGmHttp(buf[off:])
		http.GmPrint()
	}
}

func gmPcapHelp()  {
	fmt.Println("Usage: GmPcap [options]")
	fmt.Println("\t-d or --device\t:set device name")
	fmt.Println("\t-v or --version\t:show version")
	fmt.Println("\t-h or --help\t:show help")
}

func gmPcapVersion()  {
	fmt.Println("Programmer: gonglibin")
	fmt.Println("Version 1.0.0 Build on 2018.07.01")
}